package com.wd.live.module_live.view.fragment


import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.os.Build
import android.util.Log
import android.view.SurfaceView
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.wd.live.module_base.net.bean.live.LiveData
import com.wd.live.module_base.ui.base.BaseFragment
import com.wd.live.module_live.R
import com.wd.live.module_live.databinding.FragmentLiveBinding
import com.wd.live.module_live.viewmodel.LiveViewModel
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.RtcEngineConfig
import io.agora.rtc2.video.VideoCanvas
import java.io.File

@Route(path = "/live/live_fragment")
class LiveFragment : BaseFragment<LiveViewModel,FragmentLiveBinding>() {


    // 填写声网控制台中获取的 App ID
    private val appId = "e394d3be4df34e1d9f8b67bc5a007de7"
    // 填写频道名
    private val channelName = "<#Your channel name#>"

    // 填写声网控制台中生成的临时 Token
    private val token = "<#Your Token#>"

    private lateinit var mRtcEngine: RtcEngine
    private lateinit var file: File
    lateinit var labsOpenLive: LiveData
    override fun initData() {
        //封面图片
        dataBinding.coverImageLiveId.setImageResource(R.mipmap.updata).apply { RequestOptions.bitmapTransform(RoundedCorners(20)) }

        dataBinding.coverImageLiveId.setOnClickListener(View.OnClickListener {
                val intent = Intent(Intent.ACTION_PICK)
                intent.type="image/*"
                startActivityForResult(intent,0)

        })
        dataBinding.startLiveId.setOnClickListener(View.OnClickListener {
            if (dataBinding.titleTextLiveId.text==null || dataBinding.titleTextLiveId.text==""){
                Toast.makeText(context,"请输入标题",Toast.LENGTH_SHORT).show()
                return@OnClickListener
            }
            if (file==null){
                val intent = Intent(Intent.ACTION_PICK)
                intent.type="image/*"
                startActivityForResult(intent,0)
            }else{
                viewModel.postOpenLive(dataBinding.titleTextLiveId.text.toString(),file)
            }
        })
        // 如果已经授权，则初始化 RtcEngine 并加入频道
        if (checkPermissions()) {
            initializeAndJoinChannel()
        } else {
            ActivityCompat.requestPermissions(context as Activity, getRequiredPermissions(), PERMISSION_REQ_ID)
        }

        viewModel.dataOpenLive.observe(this){ it ->
            Toast.makeText(context,it.message,Toast.LENGTH_SHORT).show()

            
            if ("0000" != it.status) {
                ToastUtils.showShort(it.message ?: "直播失败")
            } else {
                it.result.let {
                        it1->
                    if (it1 != null) {
                        labsOpenLive=it1.liveData
                        Log.i("TAGiii", "initData: "+viewModel.liveId)
                        ARouter.getInstance().build("/live/live_activity")
                            .withInt("liveId",labsOpenLive.liveId)
                            .navigation()
                    }
                }
//                val intent = Intent(context, LiveActivity::class.java)
//                intent.putExtra("liveData",it.liveData)
//                startActivity(intent)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==0 && data!=null){
//            Glide.with(this)
//                .load(data.data)
//                .into(binding.imageReplace)
            file = UriUtils.uri2File(data.data)
            dataBinding.coverImageLiveId.setImageBitmap(BitmapFactory.decodeFile(UriUtils.uri2File(data.getData()).absolutePath))

        }
    }

    private val mRtcEventHandler: IRtcEngineEventHandler = object : IRtcEngineEventHandler() {
        // 成功加入频道回调
        override fun onJoinChannelSuccess(channel: String, uid: Int, elapsed: Int) {
            super.onJoinChannelSuccess(channel, uid, elapsed)
            runOnUiThread {
                Toast.makeText(
                    context,
                    "Join channel success",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }

        // 远端用户或主播加入当前频道回调
        override fun onUserJoined(uid: Int, elapsed: Int) {
            runOnUiThread {
                // 当远端用户加入频道后，显示指定 uid 的远端视频流
                setupRemoteVideo(uid)
            }
        }

        // 远端用户或主播离开当前频道回调
        override fun onUserOffline(uid: Int, reason: Int) {
            super.onUserOffline(uid, reason)
            runOnUiThread {
                Toast.makeText(
                    context,
                    "User offline: $uid",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun initializeAndJoinChannel() {

        try {
            // 创建 RtcEngineConfig 对象，并进行配置
            val config = RtcEngineConfig()
            config.mContext = activity
            config.mAppId = appId
            config.mEventHandler = mRtcEventHandler
            // 创建并初始化 RtcEngine
            mRtcEngine = RtcEngine.create(config)
        } catch (e: Exception) {
            throw IllegalArgumentException("Check the error.")
        }
        // 启用视频模块
        mRtcEngine.enableVideo()

        // 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象
        val container: FrameLayout = requireView().findViewById(R.id.local_video_view_container)
        val surfaceView = SurfaceView(context)
        container.addView(surfaceView)
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置本地视图
        mRtcEngine.setupLocalVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0))

        // 开启本地预览
        mRtcEngine.startPreview()

        // 创建 ChannelMediaOptions 对象，并进行配置
        val options = ChannelMediaOptions()
        // 设置用户角色为 BROADCASTER (主播) 或 AUDIENCE (观众)
        options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER
        // 设置频道场景为 BROADCASTING (直播场景)
        options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING
        // 发布麦克风采集的音频
        options.publishMicrophoneTrack = true
        // 发布摄像头采集的视频
        options.publishCameraTrack = true
        // 自动订阅所有音频流
        options.autoSubscribeAudio = true
        // 自动订阅所有视频流
        options.autoSubscribeVideo = true
        // 使用临时 Token 和频道名加入频道，uid 为 0 表示引擎内部随机生成用户名
        // 成功后会触发 onJoinChannelSuccess 回调
        mRtcEngine.joinChannel(token, channelName, 0, options)
    }

    private fun setupRemoteVideo(uid: Int) {


        val container: FrameLayout = requireView().findViewById(R.id.remote_video_view_container)
        val surfaceView = SurfaceView(context)
        surfaceView.setZOrderMediaOverlay(true)
        container.addView(surfaceView)
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置远端视图
        mRtcEngine!!.setupRemoteVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, uid))
    }

    private val PERMISSION_REQ_ID = 22

    // 获取体验实时音视频互动所需的录音、摄像头等权限
    private fun getRequiredPermissions(): Array<String> {
        // 判断 targetSDKVersion 31 及以上时所需的权限
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf<String>(
                Manifest.permission.RECORD_AUDIO,  // 录音权限
                Manifest.permission.CAMERA,  // 摄像头权限
                Manifest.permission.READ_PHONE_STATE,  // 读取电话状态权限
                Manifest.permission.BLUETOOTH_CONNECT // 蓝牙连接权限
            )
        } else {
            arrayOf<String>(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA
            )
        }
    }

    private fun checkPermissions(): Boolean {
        for (permission in getRequiredPermissions()) {
            val permissionCheck = context?.let { ContextCompat.checkSelfPermission(it, permission) }
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }



    // 系统权限申请回调
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (checkPermissions()) {
            initializeAndJoinChannel()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mRtcEngine != null) {
            // 停止本地视频预览
            mRtcEngine!!.stopPreview()
            // 离开频道
            mRtcEngine!!.leaveChannel()
//            mRtcEngine = null
            // 销毁引擎
            RtcEngine.destroy()
        }
    }
    override fun getViewModelClass(): Class<LiveViewModel> {
       return LiveViewModel::class.java
    }

    override fun getLayout(): Int {
        return R.layout.fragment_live
    }

}